#include "register.h"
#include "query_parser-inl.h"

int Register::start() {
    char *_val = NULL;
    long  _length = 0;
    short exec = 0;
    t_args _args;
    t_params::iterator _param_it;
    vector<Handler>::iterator _handler_it;

    if (Register::get_method_type() == GET_METHOD)
            _val = getenv("QUERY_STRING");
    else {
        if ((_val = getenv("CONTENT_LENGTH")) != NULL) {
            if ((_length = atol(_val)) != 0) {
                _val = new char[_length];
                fread(_val, _length, 1, stdin);
            } else _val = NULL;
        }
    }

    if (_val) parse(_val, &_args);
    if (Register::get_method_type() == POST_METHOD) delete _val;

    if (_args.size() != 0)
        for (
            _handler_it  = _handlers.begin();
            _handler_it != _handlers.end();
            _handler_it++
        ) {
            if (_handler_it->_params.size() == _args.size()) {
                exec = 1;
                for (
                    _param_it = _handler_it->_params.begin();
                    _param_it != _handler_it->_params.end();
                    _param_it++
                )
                    if (_args.find(*_param_it) == _args.end()) {
                        exec = 0;
                        break;
                    }

                if (exec) {
                    _handler_it->_func(&_args);
                    return 1;
                }
            }
        }
}
